package org.bridgen.runtime;

import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.bridgen.runtime.log.MendAction;
import org.bridgen.runtime.log.RecoveryAction;
import org.bridgen.runtime.model.Island;

/**
 * 
 * @author Emma Söderberg <emma add cs.lth.se>
 *
 */

public class RecoveryResult {

	private Collection<RecoveryOption> optionList;
	private RecoveryOption bestOption;
	
	public RecoveryResult(Collection<RecoveryOption> options) {
		this.optionList = options;
	}

	public String getResultAsString() {
		if (bestOption == null)
			selectBestOption();
		return RecoveryHelper.prettyPrint(bestOption.getSOF()).toString();
	}

	protected void selectBestOption() {
		System.out.println("Number of recovery options: " + optionList.size());
		for (RecoveryOption option : optionList) {
			option.getNbrFakeIslands();
			if (bestOption == null)
				bestOption = option;
			else if (bestOption.getNbrFakeIslands() > option.getNbrFakeIslands()) {
				bestOption = option;
			}
		}
	}
	
	public Map<Integer, char[]> getSuggestions() {
		HashMap<Integer, char[]> map = new HashMap<Integer, char[]>();
		if (bestOption == null)
			selectBestOption();
		for (RecoveryAction action : bestOption.getLog().getActionList()) {
			if (action instanceof MendAction) {
				MendAction mendAction = (MendAction)action;
				Island island = mendAction.getFakeIsland();
				String token = island.getValue();
				int position = island.getInterval().getStart();
				map.put(position, token.toCharArray());
				//list.add(new Suggestion(position, token));
			}
		}
		return map;
	}
	
	public class OptionComparator implements Comparator<RecoveryOption> {

		public int compare(RecoveryOption o1, RecoveryOption o2) {
			
			return 0;
		}
	}
	
	// TODO Add more directions like insert before or after position?
	public static class Suggestion {
		int position;
		String token;
		public Suggestion(int pos, String token) {
			this.position = pos;
			this.token = token;
		}
		public int getPosition() {
			return position;
		}
		public String getToken() {
			return token;
		}
		public char[] getTokenAsArray() {
			return token.toCharArray();
		}
		public String toString() {
			return "Insert " + token + " at offset " + position; 
		}
	}

}
